<?php
namespace app\know\model;

use app\know\model\KnowBaseModel;
use think\facade\Log;

class ChapterModel extends KnowBaseModel
{
    /**
     * 模型名称
     * @var string
     */
    protected $name = 'know_chapter';
	
	public function getChapterTree($relate_uuid) 
	{
		$rows = $this->where(['relate_uuid' => $relate_uuid, 'is_delete' => 0])->select()->toArray();

		$cache = [];
		// 排序
		array_multisort(array_column($rows, 'order_number'), SORT_ASC, $rows);
		array_multisort(array_column($rows, 'level'), SORT_DESC, $rows);
		
		// 初始化树形
		foreach ($rows as &$value) 
		{
			$value['name'] = htmlspecialchars_decode($value['name']);;
			$value['children'] = [];
			$cache[$value['uuid']] = $value;
		}

		foreach ($cache as &$v)
		{
			if (empty($v['parent_uuid'])) 
			{
				continue;
			}
			else
			{
				$parent = $cache[$v['parent_uuid']];
				if (!empty($parent))
				{
					Log::debug('--存在父级节点--' . $parent['name'] . '----' . $v['name']);
					array_push($cache[$v['parent_uuid']]['children'], $v);
				}
				else
				{
					Log::debug('-------xxxxxxxx------' . $v['name']);
					continue;
				}
			}
		}

		$tree = array_values(array_filter($cache, function ($var) {
			return $var['level'] == 1;
		}));
		return $tree;
	}
	
	public function getChapterPath($uuid, $relate_uuid) 
	{
		$rows = $this->where(['relate_uuid' => $relate_uuid, 'is_delete' => 0])->select()->toArray();

		$uuidArr = [$uuid];
		$i = 0;
		$uuid_t = $uuid;
		while ($i < count($rows))
		{
			$v = $rows[$i];
			if ($v['uuid'] == $uuid_t && $v['parent_uuid'])
			{
				array_push($uuidArr, $v['parent_uuid']);
				$uuid_t = $v['parent_uuid'];
				$i = -1;
			}
			++$i;
		}

		$namesArr = [];
		$i = 0;
		while ($i < count($uuidArr))
		{
			$u = $uuidArr[$i];
			for ($j = 0; $j < count($rows); $j++) { 
				if ($rows[$j]['uuid'] == $u) {
					array_push($namesArr, $rows[$j]['name']);
				}
			}
			++$i;
		}
		return implode("/", array_reverse($namesArr));
	}

}